package com.itheima.service.impl;

import com.itheima.dao.AccountDao;
import com.itheima.pojo.Account;
import com.itheima.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import javax.sql.DataSource;

@Component
public class AccountServiceImpl implements AccountService {
    @Autowired
    AccountDao accountDao;

    @Autowired
    DataSource dataSource;

    @Override
    public void transfer(String fromName, String toName, double money) {
        /*//根据名称获取账户对象
        Account fromAccount = accountDao.findByName(fromName);
        Account toAccount = accountDao.findByName(toName);

        //开始转帐
        fromAccount.setMoney(fromAccount.getMoney() - money);
        toAccount.setMoney(toAccount.getMoney() + money);
        accountDao.update(fromAccount);
        accountDao.update(toAccount);*/
        //创建事务管理器对象
        PlatformTransactionManager transactionManager = null;
        //创建事务详情对象
        TransactionDefinition transactionDefinition = null;
        //事务状态对象
        TransactionStatus transactionStatus = null;
        try {
            transactionDefinition = new DefaultTransactionDefinition();
            //必须携带数据源
            transactionManager = new DataSourceTransactionManager(dataSource);
            //开启事务
            transactionStatus = transactionManager.getTransaction(transactionDefinition);
            //根据名称获取用户信息
            Account fromAccount = accountDao.findByName(fromName);
            Account toAccount = accountDao.findByName(toName);
            //开始转账
            fromAccount.setMoney(fromAccount.getMoney() - money);
            toAccount.setMoney(toAccount.getMoney() + money);
            accountDao.update(fromAccount);
            //System.out.println(1/0);
            accountDao.update(toAccount);
            //事务提交
            transactionManager.commit(transactionStatus);
        } catch (Exception e) {
            //如果出现异常,回滚事务
            transactionManager.rollback(transactionStatus);
            e.printStackTrace();
        }
    }
}
